<template>
	<view class="order-list-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content" :style="{ height: navBarHeight + 'px' }">
				<view class="navbar-left" @click="goBack">
					<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
				</view>
				<view class="navbar-title">我的订单</view>
				<view class="navbar-right"></view>
			</view>
		</view>
		
		<!-- 订单状态筛选 -->
		<view class="order-tabs" :style="{ marginTop: (statusBarHeight + navBarHeight) + 'px' }">
			<view class="tabs-container">
				<view class="tab-item" :class="{ active: currentTab === tab.value }" v-for="tab in orderTabs"
					:key="tab.value" @click="changeTab(tab.value)">
					<text class="tab-text">{{ tab.label }}</text>
				</view>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-content" scroll-y @scrolltolower="loadMore">
			<view class="order-list">
				<view class="order-item" v-for="order in orderList" :key="order.id">
					<!-- 店铺信息 -->
					<view class="store-header" @click="goOrderDetail(order.id)">
						<view class="store-info">
							<image src="/static/icons/icon-dianpu@2x.png" class="store-icon-small" mode="aspectFill"></image>
							<text class="store-name">{{ order.storeName }}</text>
							<u-icon name="arrow-right" size="20" color="#999" class="arrow-icon"></u-icon>
						</view>
						<view class="order-status">
							<text class="status-text">{{ getStatusText(order.status) }}</text>
						</view>
					</view>

					<!-- 商品信息 -->
					<view class="goods-section" @click="goOrderDetail(order.id)">
						<image :src="baseUrl+order.images[0]" class="goods-image" mode="aspectFill"></image>
						<view class="goods-info">
							<text class="goods-name">{{ order.goodsName }}</text>
							<text class="goods-spec">规格：{{ order.specName }}</text>
						</view>
					</view>

					<!-- 订单统计 -->
					<view class="order-summary">
						<text class="summary-item">共: {{ order.totalGoods }}件商品</text>
						<text class="summary-item">分润: ¥{{ order.rebateAmount }}</text>
						<text class="summary-item">实付: ¥{{ order.totalAmount }}</text>
					</view>

					<!-- 订单操作 -->
					<view class="order-actions">
						<view class="action-btn" :class="{ 'pay-btn': action.type === 'pay' }" 
							v-for="action in getOrderActions(order)"
							:key="action.type" @click.stop="handleAction(action.type, order)">
							<text class="btn-text">{{ action.text }}</text>
						</view>
						<view class="action-btn delete-btn" @click.stop="deleteOrder(order)">
							<text class="btn-text">删除订单</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="!loading && hasMore">
				<text class="load-text">上拉加载更多</text>
			</view>

			<!-- 没有更多 -->
			<view class="no-more" v-if="!loading && !hasMore && orderList.length">
				<text class="no-more-text">没有更多订单了</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="!loading && !orderList.length">
				<image :src="imgUrl + 'img/icon-ddwk@3x.png'" class="empty-image" mode="aspectFit"></image>
				<text class="empty-text">您还没有订单信息哦~</text>
			</view>

			<!-- 加载中 -->
			<view class="loading-state" v-if="loading">
				<u-loading-icon mode="spinner" size="24"></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
		</scroll-view>

		<!-- 取消订单弹窗 -->
		<u-popup v-model="showCancelModal" mode="center" border-radius="12">
			<view class="cancel-modal">
				<view class="modal-header">
					<text class="modal-title">取消订单</text>
				</view>
				<view class="modal-content">
					<text class="modal-desc">请选择取消原因</text>
					<view class="reason-list">
						<view class="reason-item" :class="{ active: cancelReason === reason }"
							v-for="reason in cancelReasons" :key="reason" @click="selectCancelReason(reason)">
							<text class="reason-text">{{ reason }}</text>
							<u-icon name="checkmark" size="16" color="#27B387" v-if="cancelReason === reason"></u-icon>
						</view>
					</view>
				</view>
				<view class="modal-actions">
					<button class="cancel-btn" @click="hideCancelModal">
						<text class="btn-text">取消</text>
					</button>
					<button class="confirm-btn" @click="confirmCancel">
						<text class="btn-text">确定</text>
					</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import api from '@/api/index.js'
	import config from '@/api/config.js'
	import {
		inject
	} from 'vue'
	import { getToken } from '@/api/auth.js'
	export default {
		data() {
			return {
				baseUrl: inject('$baseUrl'),
				imgUrl: config.SERVER_ADDRESS,
				statusBarHeight: 0,
				navBarHeight: 44,
				currentTab: 'all',
				page: 1,
				pageSize: 10,
				loading: false,
				hasMore: true,
				showCancelModal: false,
				cancelOrderId: null,
				cancelReason: '',

				// 订单状态标签
				orderTabs: [{
						label: '全部',
						value: '1',
						count: 0
					},
					{
						label: '待付款',
						value: '2',
						count: 0
					},
					{
						label: '待发货',
						value: '3',
						count: 0
					},
					{
						label: '待收货',
						value: '4',
						count: 0
					},
					{
						label: '已完成',
						value: '5',
						count: 0
					},
				],

				// 订单列表
				orderList: [],

				// 取消原因
				cancelReasons: [
					'不想要了',
					'商品信息填错了',
					'地址信息填错了',
					'商品降价了',
					'其他原因'
				]
			}
		},
		onLoad(options) {
			// 获取系统状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			
			if (options.status) {
				this.currentTab = options.status
			}
			this.loadOrderList()
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 切换标签
			changeTab(tab) {
				this.currentTab = tab
				this.page = 1
				this.orderList = []
				this.hasMore = true
				this.loadOrderList()
			},

			// 加载订单列表
			async loadOrderList() {
				try {
					// 检查登录状态
					// const token = getToken()
					// if (!token) {
					// 	uni.navigateTo({
					// 		url: '/pages/login/login'
					// 	})
					// 	return
					// }

					this.loading = true

					const result = await api.orderApi.getOrderList({
						page: this.page,
						limit: this.pageSize,
						sel_type: this.currentTab === 'all' ? 1 : this.currentTab
					})

					if (result.r === 0) {
						const data = result.data

						// 处理订单数据
						const orderList = data.lists ? data.lists.map(order => ({
							id: order.id,
							orderNo: order.order_num,
							status: order.state,
							createTime: new Date(order.created * 1000).toLocaleString(),
							totalAmount: order.pay_amount,
							rebateAmount: order.rebate_amount,
							totalGoods: order.goods_total_num,
							storeName: order.manufac_name,
							storeId: order.manufac_id,
							manufacLogo: order.manufac_logo,
							goodsName: order.goods_name,
							specName: order.spec_name,
							images: order.img_path || [],
							deadline: order.deadline,
							label: order.label
						})) : []

						if (this.page === 1) {
							this.orderList = orderList
						} else {
							this.orderList.push(...orderList)
						}

						this.hasMore = orderList.length >= this.pageSize

						// 更新标签计数
						if (data.status_count) {
							this.orderTabs.forEach(tab => {
								if (data.status_count[tab.value] !== undefined) {
									tab.count = data.status_count[tab.value]
								}
							})
						}
					} else {
						console.error('获取订单列表失败:', result.msg)
						this.orderList = []
					}
				} catch (error) {
					console.error('加载订单列表失败:', error)
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 生成模拟数据
			generateMockData() {
				const list = []
				const statuses = ['pending', 'paid', 'shipped', 'delivered', 'completed', 'cancelled']

				for (let i = 0; i < this.pageSize; i++) {
					const id = (this.page - 1) * this.pageSize + i + 1
					const status = this.currentTab === 'all' ? statuses[Math.floor(Math.random() * statuses.length)] : this
						.currentTab

					list.push({
						id,
						orderNo: `YP${Date.now()}${id}`,
						status,
						createTime: '2024-01-15 10:30:00',
						totalAmount: (Math.random() * 500 + 50).toFixed(2),
						totalGoods: Math.floor(Math.random() * 5) + 1,
						goodsList: [{
								id: 1,
								title: 'iPhone 15 Pro Max 256GB 深空黑色',
								image: '/static/goods1.jpg',
								spec: '深空黑色 256GB',
								price: '9999.00',
								quantity: 1
							},
							{
								id: 2,
								title: 'AirPods Pro 第三代',
								image: '/static/goods2.jpg',
								spec: '白色',
								price: '1999.00',
								quantity: 1
							}
						].slice(0, Math.floor(Math.random() * 2) + 1)
					})
				}

				return {
					list,
					total: 50
				}
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.page++
					this.loadOrderList()
				}
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: '待付款',
					1: '待发货',
					2: '待收货',
					3: '已收货',
					10: '交易完成',
					11: '交易关闭(会员取消)',
					12: '交易关闭(客服取消)',
					13: '交易关闭(支付超时自动关闭)',
					14: '交易关闭(支付超时自动关闭)',
					15: '交易关闭(退款商家同意退款)'
				}
				return statusMap[status] || '待付款'
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					0: 'status-pending',
					1: 'status-paid',
					2: 'status-shipped',
					3: 'status-delivered',
					4: 'status-completed',
					5: 'status-cancelled'
				}
				return classMap[status] || 'status-pending'
			},

			// 获取订单操作按钮
			getOrderActions(order) {
				const actions = []

				switch (order.status) {
					case 0: // 待付款
						actions.push({
							type: 'cancel',
							text: '取消订单'
						}, {
							type: 'pay',
							text: '付款'
						})
						break
					case 1: // 待发货
						actions.push({
							type: 'refund',
							text: '申请退款'
						})
						break
					case 2: // 待收货
						actions.push({
							type: 'logistics',
							text: '查看物流'
						}, {
							type: 'confirm',
							text: '确认收货'
						})
						break
					case 3: // 已收货
					case 10: // 交易完成
						// 只显示删除订单按钮（在模板中固定显示）
						break
					case 11: // 交易关闭(会员取消)
					case 12: // 交易关闭(客服取消)
					case 13: // 交易关闭(支付超时自动关闭)
					case 14: // 交易关闭(支付超时自动关闭)
					case 15: // 交易关闭(退款商家同意退款)
						// 只显示删除订单按钮（在模板中固定显示）
						break
				}

				return actions
			},

			// 处理订单操作
			handleAction(type, order) {
				switch (type) {
					case 'cancel':
						this.showCancelOrder(order)
						break
					case 'pay':
						this.payOrder(order)
						break
					case 'refund':
						this.applyRefund(order)
						break
					case 'logistics':
						this.viewLogistics(order)
						break
					case 'confirm':
						this.confirmReceive(order)
						break
					case 'evaluate':
						this.evaluateOrder(order)
						break
					case 'buy_again':
						this.buyAgain(order)
						break
					case 'delete':
						this.deleteOrder(order)
						break
				}
			},

			// 显示取消订单弹窗
			showCancelOrder(order) {
				this.cancelOrderId = order.id
				this.cancelReason = ''
				this.showCancelModal = true
			},

			// 隐藏取消订单弹窗
			hideCancelModal() {
				this.showCancelModal = false
				this.cancelOrderId = null
				this.cancelReason = ''
			},

			// 选择取消原因
			selectCancelReason(reason) {
				this.cancelReason = reason
			},

			// 确认取消订单
			async confirmCancel() {
				if (!this.cancelReason) {
					uni.showToast({
						title: '请选择取消原因',
						icon: 'none'
					})
					return
				}

				try {
					uni.showLoading({
						title: '取消中...'
					})

					const result = await api.orderApi.cancelOrder({
						order_id: this.cancelOrderId,
						cancel_reason: this.cancelReason
					})

					uni.hideLoading()

					if (result.r === 0) {
						uni.showToast({
							title: '订单已取消',
							icon: 'success'
						})

						this.hideCancelModal()
						this.page = 1
						this.orderList = []
						this.loadOrderList()
					} else {
						uni.showToast({
							title: result.msg || '取消失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('取消订单失败:', error)
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				}
			},

			// 支付订单
			payOrder(order) {
				uni.navigateTo({
					url: `/pages/order/pay?orderId=${order.id}`
				})
			},

			// 申请退款
			applyRefund(order) {
				uni.navigateTo({
					url: `/pages/order/refund?order_id=${order.id}&order_num=${order.orderNo}`
				})
			},

			// 查看物流
			viewLogistics(order) {
				uni.navigateTo({
					url: `/pages/order/logistics?orderId=${order.id}`
				})
			},

			// 确认收货
			confirmReceive(order) {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '确认中...'
								})

								const result = await api.orderApi.confirmReceive({
									order_id: order.id
								})

								uni.hideLoading()

								if (result.r === 0) {
									uni.showToast({
										title: '确认收货成功',
										icon: 'success'
									})
									this.page = 1
									this.orderList = []
									this.loadOrderList()
								} else {
									uni.showToast({
										title: result.msg || '确认收货失败',
										icon: 'none'
									})
								}
							} catch (error) {
								uni.hideLoading()
								console.error('确认收货失败:', error)
								uni.showToast({
									title: '网络异常，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 评价订单
			evaluateOrder(order) {
				uni.navigateTo({
					url: `/pages/order/evaluate?orderId=${order.id}`
				})
			},

			// 再次购买
			async buyAgain(order) {
				try {
					uni.showLoading({
						title: '添加中...'
					})

					const result = await api.orderApi.buyAgain({
						order_id: order.id
					})

					uni.hideLoading()

					if (result.r === 0) {
						uni.showToast({
							title: '已加入购物车',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: result.msg || '添加失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('再次购买失败:', error)
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					})
				}
			},

			// 删除订单
			deleteOrder(order) {
				uni.showModal({
					title: '删除订单',
					content: '确定要删除此订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中...'
								})

								const result = await api.orderApi.deleteOrder({
									order_id: order.id
								})

								uni.hideLoading()

								if (result.r === 0) {
									uni.showToast({
										title: '订单已删除',
										icon: 'success'
									})
									this.page = 1
									this.orderList = []
									this.loadOrderList()
								} else {
									uni.showToast({
										title: result.msg || '删除失败',
										icon: 'none'
									})
								}
							} catch (error) {
								uni.hideLoading()
								console.error('删除订单失败:', error)
								uni.showToast({
									title: '网络异常，请重试',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			// 跳转订单详情
			goOrderDetail(orderId) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${orderId}`
				})
			},

			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-list-page {
		background-color: #f5f5f5;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
		background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);

		.navbar-content {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;

			.navbar-left {
				width: 60rpx;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: flex-start;
			}

			.navbar-title {
				flex: 1;
				font-size: 36rpx;
				font-weight: 500;
				color: #fff;
				text-align: center;
			}

			.navbar-right {
				width: 60rpx;
			}
		}
	}

	.nav-header {
		height: 100rpx;
		background-color: #FF5722;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;

		.nav-back {
			padding: 10rpx;

			.back-icon {
				font-size: 48rpx;
				color: #fff;
				font-weight: bold;
			}
		}

		.nav-title {
			font-size: 36rpx;
			font-weight: 500;
			color: #fff;
		}

		.nav-right {
			width: 60rpx;
		}
	}

	.order-tabs {
		background-color: #fff;
		border-bottom: 2rpx solid #f0f0f0;

		.tabs-container {
			display: flex;
			padding: 0;

			.tab-item {
				position: relative;
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				flex: 1;

				&.active {
					.tab-text {
						color: #FF5722;
						font-weight: 500;
					}

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 0;
						right: 0;
						height: 4rpx;
						background-color: #FF5722;
					}
				}

				.tab-text {
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}

	.order-content {
		flex: 1;
		margin-top: 20rpx;

		.order-list {
			.order-item {
				background-color: #fff;
				margin-bottom: 20rpx;
				overflow: hidden;

				.store-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 24rpx 30rpx;
					border-bottom: 1rpx solid #f5f5f5;

					.store-info {
						display: flex;
						align-items: center;
						flex: 1;
						overflow: hidden;

						.store-icon-small {
							width: 40rpx;
							height: 40rpx;
							border-radius: 8rpx;
							margin-right: 12rpx;
							flex-shrink: 0;
						}

						.store-name {
							font-size: 28rpx;
							color: #333;
							flex: 1;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.arrow-icon {
							margin-left: 8rpx;
							flex-shrink: 0;
						}
					}

					.order-status {
						.status-text {
							font-size: 28rpx;
							color: #FF6B35;
						}
					}
				}

				.goods-section {
					display: flex;
					padding: 30rpx;
					gap: 24rpx;

					.goods-image {
						width: 160rpx;
						height: 160rpx;
						border-radius: 12rpx;
						flex-shrink: 0;
					}

					.goods-info {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;

						.goods-name {
							font-size: 28rpx;
							color: #333;
							margin-bottom: 16rpx;
							line-height: 1.5;
						}

						.goods-spec {
							font-size: 24rpx;
							color: #999;
						}
					}
				}

				.order-summary {
					display: flex;
					justify-content: flex-end;
					align-items: center;
					gap: 20rpx;
					padding: 30rpx;
					border-top: 1rpx solid #f5f5f5;
					border-bottom: 1rpx solid #f5f5f5;

					.summary-item {
						font-size: 28rpx;
						color: #666;
						white-space: nowrap;
					}
				}

				.order-actions {
					display: flex;
					justify-content: flex-end;
					gap: 20rpx;
					padding: 30rpx;

					.action-btn {
						height: 60rpx;
						padding: 0 32rpx;
						border: 2rpx solid #FF6B35;
						border-radius: 12rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						background-color: #fff;

						.btn-text {
							font-size: 26rpx;
							color: #FF6B35;
						}

						&.pay-btn {
							background-color: #FF6B35;
							
							.btn-text {
								color: #fff;
							}
						}
					}
				}
			}
		}

		.load-more,
		.no-more {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.load-text,
			.no-more-text {
				font-size: 24rpx;
				color: #999;
			}
		}

		.empty-state {
			padding: 120rpx 40rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.empty-image {
				width: 240rpx;
				height: 240rpx;
				margin-bottom: 40rpx;
			}

			.empty-text {
				font-size: 32rpx;
				color: #666;
				margin-bottom: 16rpx;
			}

			.empty-desc {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 40rpx;
			}

			.go-shop-btn {
				width: 240rpx;
				height: 72rpx;
				background: linear-gradient(135deg, #27B387 0%, #1e9c6f 100%);
				border-radius: 36rpx;
				border: none;
				display: flex;
				align-items: center;
				justify-content: center;

				.btn-text {
					font-size: 28rpx;
					color: #fff;
				}
			}
		}

		.loading-state {
			height: 400rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			gap: 20rpx;

			.loading-text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}

	.cancel-modal {
		width: 560rpx;
		background-color: #fff;
		border-radius: 24rpx;
		overflow: hidden;

		.modal-header {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-bottom: 2rpx solid #f0f0f0;

			.modal-title {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.modal-content {
			padding: 40rpx 30rpx;

			.modal-desc {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 30rpx;
			}

			.reason-list {
				.reason-item {
					height: 80rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					padding: 0 20rpx;
					border-radius: 8rpx;
					margin-bottom: 16rpx;

					&.active {
						background-color: #f0f9f6;

						.reason-text {
							color: #27B387;
						}
					}

					.reason-text {
						font-size: 28rpx;
						color: #333;
					}
				}
			}
		}

		.modal-actions {
			height: 100rpx;
			display: flex;
			border-top: 2rpx solid #f0f0f0;

			.cancel-btn,
			.confirm-btn {
				flex: 1;
				height: 100%;
				border: none;
				background-color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;

				.btn-text {
					font-size: 32rpx;
				}
			}

			.cancel-btn {
				border-right: 2rpx solid #f0f0f0;

				.btn-text {
					color: #999;
				}
			}

			.confirm-btn {
				.btn-text {
					color: #27B387;
					font-weight: 500;
				}
			}
		}
	}
</style>